## Determines which precincts lie on county borders and saves a data frame with entries that indicates this.

library(rgdal)
library(rgeos)
library(dplyr)

countyshp <- readOGR(dsn = "../shapes/CountyBoundary", layer = "CountyBoundary")
prec2016shp <- readOGR(dsn = "../shapes/SBE_PRECINCTS_20161004", layer = "Precincts")

## Replace county name spaces with underscores in both county and precinct shapefiles
countyshp$NAME <- gsub(" ", "_", countyshp$NAME)
prec2016shp$COUNTY_NAM <- gsub(" ", "_", prec2016shp$COUNTY_NAM)

## extend county buffers by 100 to account for inconsistencies between
## county and precinct shape files
buffed_counties <- gBuffer(countyshp, width = 100, byid = TRUE)

## intersect buffed counties and precincts; result here is a data
## frame with one row for each precinct and (100) columns indicating
## if a county is touched
intersects <- data.frame(gIntersects(buffed_counties, prec2016shp, byid = TRUE))
names(intersects) <- as.character(countyshp$NAME)

## clean up border precincts (so a precinct in county X is not listed in county Y)
border_precincts <- intersects
for (i in 1:nrow(buffed_counties)) {
  border_precincts[,i] <- intersects[,i] & prec2016shp$COUNTY_NAM != names(intersects)[i]
}

## make map for each county (visual inspection) and a map of all border precincts
pdf(file = "nc_counties_and_border_precincts.pdf")
for (i in 1:nrow(buffed_counties)) {
  plot(prec2016shp[border_precincts[, i], ], main = paste(countyshp$NAME[i], "COUNTY"))
  border_counties <- gTouches(countyshp[i,], countyshp, byid = TRUE)
  plot(countyshp[border_counties[ ,1], ], add = TRUE, border = "green")
  plot(countyshp[i,], add = TRUE, col = "red", density = 15)
}
dev.off()

return_sum_true <- function(x) {
  sum(x == TRUE) > 0
}
is_border_precinct <- apply(border_precincts[-c(1:2),], 1 ,return_sum_true)

pdf(file = "nc-border-precincts.pdf")
plot(prec2016shp[is_border_precinct == TRUE,], border = "blue")
plot(countyshp, add = TRUE, border = "green")
dev.off()

## add various precinct identifiers to the border_precincts matrix for
## merging with voter file
border_precincts <- cbind (prec2016shp$PREC_ID,
                           prec2016shp$ENR_DESC, 
                           prec2016shp$COUNTY_NAM,
                           prec2016shp$COUNTY_ID,
                           border_precincts)

## clean up column names
names(border_precincts) <- gsub("^prec.*\\$","",names(border_precincts))

## some of the precinct identifiers have odd windows-related end of line markings -- get rid of these
border_precincts$ENR_DESC <- gsub("\r\n", "", border_precincts$ENR_DESC)

## and save 
write.table (border_precincts,
             file = "border_precincts.csv",
             row.names = FALSE,
             col.names = TRUE,
             quote = FALSE,
             sep = "\t")



